package com.shxzz.easy12306.framework.starter.user.core;

import com.shxzz.easy12306.framework.starter.user.constant.UserConstant;
import jakarta.servlet.*;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.util.StringUtils;

import java.io.IOException;


/**
 * 用户信息提取过滤器
 * @author shxzz
 * @create 2024-02-24-18:58
 */
public class UserTransmitFilter implements Filter {
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest httpServletRequest = (HttpServletRequest) servletRequest;
        String userId = httpServletRequest.getHeader(UserConstant.USER_ID_KEY);
        if(StringUtils.hasLength(userId)) {
            String username = httpServletRequest.getHeader(UserConstant.USER_NAME_KEY);
            String token = httpServletRequest.getHeader(UserConstant.USER_TOKEN_KEY);
            String realName = httpServletRequest.getHeader(UserConstant.REAL_NAME_KEY);
            UserContext.setUser(new UserInfoDTO(userId, username, realName, token));
        }

        try {
            filterChain.doFilter(servletRequest, servletResponse);
        } finally {
            UserContext.removeUser();
        }

    }
}
